# RISC-V 操作系統項目 Git 同步腳本
# 支持一鍵推送、拉取、狀態檢查等功能

param(
    [string]$Action = "status",  # 默認操作：status, push, pull, init, clone
    [string]$Remote = "origin",  # 遠程倉庫名稱
    [string]$Branch = "main"     # 分支名稱
)

# 顏色定義
$Colors = @{
    Success = "Green"
    Warning = "Yellow"
    Error = "Red"
    Info = "Cyan"
    Header = "Magenta"
}

function Write-ColorText {
    param([string]$Text, [string]$Color = "White")
    Write-Host $Text -ForegroundColor $Color
}

function Show-Header {
    Write-ColorText "`n=== RISC-V 操作系統項目 Git 同步工具 ===" $Colors.Header
    Write-ColorText "當前目錄: $(Get-Location)" $Colors.Info
    Write-ColorText "操作: $Action | 遠程: $Remote | 分支: $Branch" $Colors.Info
    Write-ColorText ""
}

function Test-GitRepository {
    if (Test-Path ".git") {
        return $true
    } else {
        Write-ColorText "❌ 當前目錄不是 Git 倉庫" $Colors.Error
        return $false
    }
}

function Test-GitInstalled {
    try {
        $version = git --version
        Write-ColorText "✅ Git 已安裝: $version" $Colors.Success
        return $true
    } catch {
        Write-ColorText "❌ Git 未安裝" $Colors.Error
        Write-ColorText "請訪問 https://git-scm.com/download/win 下載安裝" $Colors.Warning
        return $false
    }
}

function Show-GitStatus {
    Write-ColorText "`n=== Git 狀態檢查 ===" $Colors.Info
    
    if (-not (Test-GitRepository)) { return }
    
    # 檢查工作區狀態
    $status = git status --porcelain
    if ($status) {
        Write-ColorText "📝 有未提交的更改:" $Colors.Warning
        git status --short
    } else {
        Write-ColorText "✅ 工作區乾淨" $Colors.Success
    }
    
    # 檢查分支信息
    $currentBranch = git branch --show-current
    Write-ColorText "🌿 當前分支: $currentBranch" $Colors.Info
    
    # 檢查遠程倉庫
    $remotes = git remote -v
    if ($remotes) {
        Write-ColorText "🔗 遠程倉庫:" $Colors.Info
        $remotes
    } else {
        Write-ColorText "⚠️  未配置遠程倉庫" $Colors.Warning
    }
    
    # 檢查提交歷史
    $log = git log --oneline -5
    if ($log) {
        Write-ColorText "`n📚 最近提交:" $Colors.Info
        $log
    }
}

function Initialize-GitRepository {
    Write-ColorText "`n=== 初始化 Git 倉庫 ===" $Colors.Info
    
    if (Test-Path ".git") {
        Write-ColorText "✅ Git 倉庫已存在" $Colors.Success
        return
    }
    
    try {
        git init
        Write-ColorText "✅ Git 倉庫初始化完成" $Colors.Success
        
        # 創建 .gitignore
        $gitignore = @"
# 編譯產物
*.o
*.elf
*.bin
*.img
*.iso

# 調試文件
*.dSYM/
*.su
*.idb
*.pdb

# 日誌文件
*.log

# 臨時文件
*.tmp
*.temp
*~

# IDE 文件
.vscode/
.idea/
*.swp
*.swo

# 系統文件
.DS_Store
Thumbs.db

# 備份文件
*.bak
*.backup
"@
        $gitignore | Out-File -FilePath ".gitignore" -Encoding UTF8
        Write-ColorText "✅ 創建 .gitignore 文件" $Colors.Success
        
    } catch {
        Write-ColorText "❌ Git 倉庫初始化失敗: $($_.Exception.Message)" $Colors.Error
    }
}

function Add-RemoteRepository {
    param([string]$RemoteName, [string]$RemoteUrl)
    
    Write-ColorText "`n=== 配置遠程倉庫 ===" $Colors.Info
    
    # 檢查是否已存在
    $existing = git remote get-url $RemoteName 2>$null
    if ($existing) {
        Write-ColorText "✅ 遠程倉庫 $RemoteName 已存在: $existing" $Colors.Success
        return
    }
    
    try {
        git remote add $RemoteName $RemoteUrl
        Write-ColorText "✅ 遠程倉庫 $RemoteName 添加成功" $Colors.Success
    } catch {
        Write-ColorText "❌ 添加遠程倉庫失敗: $($_.Exception.Message)" $Colors.Error
    }
}

function Push-ToRemote {
    Write-ColorText "`n=== 推送到遠程倉庫 ===" $Colors.Info
    
    if (-not (Test-GitRepository)) { return }
    
    try {
        # 添加所有更改
        Write-ColorText "📝 添加文件到暫存區..." $Colors.Info
        git add .
        
        # 檢查是否有更改
        $status = git status --porcelain
        if (-not $status) {
            Write-ColorText "ℹ️  沒有更改需要提交" $Colors.Info
            return
        }
        
        # 提交更改
        $commitMessage = "更新 RISC-V 操作系統項目 - $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
        Write-ColorText "💾 提交更改: $commitMessage" $Colors.Info
        git commit -m $commitMessage
        
        # 推送到遠程
        Write-ColorText "🚀 推送到 $Remote/$Branch..." $Colors.Info
        git push -u $Remote $Branch
        
        Write-ColorText "✅ 推送完成！" $Colors.Success
        
    } catch {
        Write-ColorText "❌ 推送失敗: $($_.Exception.Message)" $Colors.Error
        Write-ColorText "💡 提示: 請檢查網路連接和遠程倉庫配置" $Colors.Warning
    }
}

function Pull-FromRemote {
    Write-ColorText "`n=== 從遠程倉庫拉取 ===" $Colors.Info
    
    if (-not (Test-GitRepository)) { return }
    
    try {
        Write-ColorText "📥 從 $Remote/$Branch 拉取最新更改..." $Colors.Info
        git pull $Remote $Branch
        
        Write-ColorText "✅ 拉取完成！" $Colors.Success
        
    } catch {
        Write-ColorText "❌ 拉取失敗: $($_.Exception.Message)" $Colors.Error
        Write-ColorText "💡 提示: 請檢查網路連接和遠程倉庫配置" $Colors.Warning
    }
}

function Clone-Repository {
    param([string]$RepositoryUrl, [string]$LocalPath = ".")
    
    Write-ColorText "`n=== 克隆倉庫 ===" $Colors.Info
    
    try {
        Write-ColorText "📥 克隆倉庫: $RepositoryUrl" $Colors.Info
        git clone $RepositoryUrl $LocalPath
        
        Write-ColorText "✅ 克隆完成！" $Colors.Success
        
    } catch {
        Write-ColorText "❌ 克隆失敗: $($_.Exception.Message)" $Colors.Error
    }
}

function Show-Help {
    Write-ColorText "`n=== 使用說明 ===" $Colors.Header
    Write-ColorText ""
    Write-ColorText "基本用法:" $Colors.Info
    Write-ColorText "  .\git-sync.ps1 [操作] [參數]" $Colors.Warning
    Write-ColorText ""
    Write-ColorText "可用操作:" $Colors.Info
    Write-ColorText "  status    - 檢查 Git 狀態（默認）" $Colors.Warning
    Write-ColorText "  push      - 推送到遠程倉庫" $Colors.Warning
    Write-ColorText "  pull      - 從遠程倉庫拉取" $Colors.Warning
    Write-ColorText "  init      - 初始化 Git 倉庫" $Colors.Warning
    Write-ColorText "  clone     - 克隆倉庫" $Colors.Warning
    Write-ColorText "  help      - 顯示此幫助信息" $Colors.Warning
    Write-ColorText ""
    Write-ColorText "參數:" $Colors.Info
    Write-ColorText "  -Remote   遠程倉庫名稱（默認: origin）" $Colors.Warning
    Write-ColorText "  -Branch   分支名稱（默認: main）" $Colors.Warning
    Write-ColorText ""
    Write-ColorText "示例:" $Colors.Info
    Write-ColorText "  .\git-sync.ps1                    # 檢查狀態" $Colors.Warning
    Write-ColorText "  .\git-sync.ps1 push               # 推送更改" $Colors.Warning
    Write-ColorText "  .\git-sync.ps1 pull               # 拉取更改" $Colors.Warning
    Write-ColorText "  .\git-sync.ps1 init               # 初始化倉庫" $Colors.Warning
    Write-ColorText "  .\git-sync.ps1 clone https://gitee.com/user/repo.git" $Colors.Warning
    Write-ColorText ""
}

# 主程序
Show-Header

# 檢查 Git 是否安裝
if (-not (Test-GitInstalled)) {
    exit 1
}

# 根據操作執行相應功能
switch ($Action.ToLower()) {
    "status" {
        Show-GitStatus
    }
    "push" {
        Show-GitStatus
        Push-ToRemote
    }
    "pull" {
        Pull-FromRemote
    }
    "init" {
        Initialize-GitRepository
        # 自動配置 Gitee 遠程倉庫
        Add-RemoteRepository "origin" "https://gitee.com/Antelope693/whu-cs-os.git"
        Add-RemoteRepository "github" "https://github.com/your-username/riscv-os.git"
    }
    "clone" {
        if ($args.Count -gt 0) {
            Clone-Repository $args[0]
        } else {
            Write-ColorText "❌ 請提供要克隆的倉庫 URL" $Colors.Error
            Write-ColorText "用法: .\git-sync.ps1 clone <倉庫URL>" $Colors.Warning
        }
    }
    "help" {
        Show-Help
    }
    default {
        Write-ColorText "❌ 未知操作: $Action" $Colors.Error
        Show-Help
    }
}

Write-ColorText "`n=== 操作完成 ===" $Colors.Header
